package com.kinon.ogt.view.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.kinon.ogt.R;
import com.kinon.ogt.api.OgtApi;
import com.kinon.ogt.api.exception.ApiException;
import com.kinon.ogt.api.service.ServiceFactory;
import com.kinon.ogt.utils.PhoneUtils;
import com.kinon.ogt.utils.RegExUtils;
import com.kinon.ogt.utils.RxUtils;
import com.kinon.ogt.utils.SPrefsUtils;
import com.kinon.ogt.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 佛祖保佑 永无BUG
 *
 * @author 339
 * @date 2018/5/16
 */
public class SignInActivity extends AppCompatActivity {

    @BindView(R.id.et_sign_in_phone_number)
    EditText mEtPhoneNumber;
    @BindView(R.id.et_sign_in_password)
    EditText mEtPassword;
    @BindView(R.id.btn_sign_in)
    Button mBtnSignIn;
    @BindView(R.id.cb_service_terms)
    CheckBox mCbServiceTerms;

    private boolean acceptTheServiceTerms = true;

    private Disposable mDisposable;
    private OgtApi mOgtApi;

    private String mPhoneNumber;
    private String mPassword;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
        mOgtApi = ServiceFactory.getOgtApi();

        mPhoneNumber = SPrefsUtils.readUsername();
        mPassword = SPrefsUtils.readPassword();
    }

    private void initView() {
        mEtPhoneNumber.setText(mPhoneNumber);
        mEtPassword.setText(mPassword);

        mEtPhoneNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                onGetFocus(mEtPhoneNumber);
                onRemoveFocus(mEtPassword);
            }
        });

        mEtPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                onGetFocus(mEtPassword);
                onRemoveFocus(mEtPhoneNumber);
            }
        });

        mCbServiceTerms.setChecked(acceptTheServiceTerms);

        mCbServiceTerms.setOnCheckedChangeListener((buttonView, isChecked) ->
                acceptTheServiceTerms = isChecked);
    }

    private void onGetFocus(EditText editText) {
        editText.setBackground(getDrawable(R.drawable.img_bg_et_selected));
    }

    private void onRemoveFocus(EditText editText) {
        editText.setBackground(getDrawable(R.drawable.img_bg_et_unselected));
    }

    @OnClick(R.id.btn_sign_in)
    public void onSignInClicked() {
        String phoneNumber = mEtPhoneNumber.getText().toString();
        String password = mEtPassword.getText().toString();

        if (!acceptTheServiceTerms) {
            Toast.makeText(this, "需要接受服务条款！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!RegExUtils.isPhoneNumValid(phoneNumber) || !RegExUtils.isPasswordValid(password)) {
            Toast.makeText(this, "请输入正确的帐号密码！", Toast.LENGTH_SHORT).show();
            return;
        }

        attemptSignIn(phoneNumber, password);
    }

    private void attemptSignIn(String phoneNumber, String password) {
        mBtnSignIn.setEnabled(false);
        mDisposable = mOgtApi.attemptSignIn(phoneNumber, password, 1, PhoneUtils.getSystemModel())
                .compose(RxUtils.rxSchedulerHelper())
                .compose(RxUtils.handleResult())
                .subscribe(result -> saveUserInfo(phoneNumber, password, result),
                        throwable -> {
                            mBtnSignIn.setEnabled(true);
                            ToastUtils.showShort(SignInActivity.this, ((ApiException) throwable).getMsg());
                        });
    }

    private void saveUserInfo(String phoneNum, String password, String result) {
        SPrefsUtils.writeUsername(phoneNum);
        SPrefsUtils.writePassword(password);
        SPrefsUtils.writeToken(result);
        startActivity(new Intent(SignInActivity.this, MainActivity.class));
        finish();
    }

    @OnClick(R.id.tv_sign_in_forget_password)
    public void onForgetPasswordClicked() {
    }

    @OnClick(R.id.tv_sign_up)
    public void onSignUpClicked() {
        startActivity(new Intent(SignInActivity.this, SignUpActivity.class));
    }

    @OnClick(R.id.tv_service_terms)
    public void onServiceTermsClicked() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDisposable) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
